//
//  NSString+MGAdd.m
//  MGKit
//
//  Created by 赖锋海 on 2018/7/12.
//

#import "NSString+MGAdd.h"

@implementation NSString (MGAdd)

+ (NSString *)localizedStringForKey:(NSString *)key value:(nullable NSString *)value table:(nullable NSString *)tableName bundle:(nullable NSBundle *)bundle {
    NSString *string = [bundle localizedStringForKey:key value:value table:tableName];
    return string;
}

+ (NSString *)localizedStringForKey:(NSString *)key tableName:(nullable NSString *)tableName bundleName:(nullable NSString *)bundleName {
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:bundleName ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *string = [bundle localizedStringForKey:key value:@"" table:tableName];
    return string;
}

+ (NSString *)localizedStringForKey:(NSString *)key value:(nullable NSString *)value tableName:(nullable NSString *)tableName bundleName:(nullable NSString *)bundleName {
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:bundleName ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *string = [bundle localizedStringForKey:key value:value table:tableName];
    return string;
}

//+ (NSString *)stringFromTimeInterval:(NSTimeInterval)timeInterval {
//    NSString *dateString = nil;
//    NSInteger timeToDisplay = 0;
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000];
//    NSTimeInterval timeSinceLastUpdate = -1 * [date timeIntervalSinceNow] - 600;
//    if(timeSinceLastUpdate < 3600) {
//        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 60);
//        dateString = timeToDisplay < 2 ? [NSString stringWithFormat:@"刚刚"] : [NSString stringWithFormat:@"%ld分钟前",(long)timeToDisplay];
//    } else if (timeSinceLastUpdate < 86400) {
//        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 3600);
//        dateString = [NSString stringWithFormat:@"%ld小时前",(long)timeToDisplay];
//    } else if (timeSinceLastUpdate < 2592000) {
//        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 86400);
//        dateString = [NSString stringWithFormat:@"%ld天前",(long)timeToDisplay];
//    } else {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        dateString = [dateFormatter stringFromDate:date];
//    }
//    return dateString;
//}

+ (NSString *)stringFromTimeInterval:(NSTimeInterval)timeInterval {
    timeInterval = timeInterval/1000;
    NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
    NSTimeInterval distanceTime = now - timeInterval;
    NSString * distanceStr;
    
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *currentComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSInteger year = [currentComponents year];
    
    NSDate *beDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateComponents *newComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:beDate];
    NSInteger newYear = [newComponents year];
    BOOL isCurrentYear = NO;
    if (newYear == year) {
        isCurrentYear = YES;
    }
    
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString *timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {//小于一分钟
        distanceStr = @"刚刚";
    }
    else if (distanceTime <60*60) {//时间小于一个小时
        distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
    }
    else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
        distanceStr = [NSString stringWithFormat:@"%@",timeStr];
    }
    else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        if ([nowDay integerValue] - [lastDay integerValue] == 1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            //            distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
            distanceStr = @"昨天";
        }
        else{
            [df setDateFormat:@"MM-dd"];
            distanceStr = [df stringFromDate:beDate];
        }
    }
    else if(isCurrentYear){
        [df setDateFormat:@"MM-dd"];
        distanceStr = [df stringFromDate:beDate];
    }
    else{
        [df setDateFormat:@"yyyy-MM-dd"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}

+ (BOOL)isNilString:(NSString *)string {
    return [string isEqual:[NSNull null]] || string == nil || string.length == 0;
}

+ (NSString *)replaceNull:(NSString *)string {
    if(string.length == 0 || string == nil) {
        return @"";
    } else {
        return string;
    }
}

+ (NSString *)replaceBigNumber:(NSString *)string {
    float number = [string floatValue];
    if(number/100000000 >= 1) {
        number = number/10000;
        if(number/1000 >= 1) {
            return [NSString stringWithFormat:@"%@w",[NSString formatBigNumber:number]];
        } else {
            return [NSString stringWithFormat:@"%.1fw",number];
        }
    } else if(number/10000 >= 1) {
        number = number/10000;
        if(number/1000 >= 1) {
            return [NSString stringWithFormat:@"%@w",[NSString formatBigNumber:number]];
        } else {
            return [NSString stringWithFormat:@"%.1fw",number];
        }
    } else if(number/1000 >= 1) {
        string = [NSString formatBigNumber:number];
    }
    return string;
}

+ (NSString *)formatBigNumber:(float)number {
    int count = 0;
    int tempNumber = number;
    while (tempNumber != 0) {
        count++;
        tempNumber /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithFormat:@"%d",(int)number];
    NSMutableString *tempString = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *subString = [string substringWithRange:rang];
        [tempString insertString:subString atIndex:0];
        [tempString insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [tempString insertString:string atIndex:0];
    return tempString;
}

+ (NSMutableDictionary *)getURLParametersWithURLString:(NSString *)urlString {
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return nil;
    }
    //查找参数
    NSRange range = [urlString rangeOfString:@"?"];
    //字符串容错
    if(range.location == NSNotFound || range.location == urlString.length - 1) {
        return nil;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //截取参数
    NSString *parametersString = [urlString substringFromIndex:range.location + 1];
    //判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        //多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        for (NSString *keyValuePair in urlComponents) {
            //生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            //Key不能为nil
            if (key == nil) {
                continue;
            }
            //只有key，或value为空
            if (pairComponents.count == 1 || value == nil) {
                value = @"";
            }
            //设置值，有重复值则以最后一个为准
            [params setValue:value forKey:key];
        }
    } else {
        // 单个参数
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        // Key不能为nil
        if (key == nil) {
            return nil;
        }
        //只有key，或value为空
        if (pairComponents.count == 1 || value == nil) {
            value = @"";
        }
        // 设置值
        [params setValue:value forKey:key];
    }
    return params;
}

+ (NSString *)getParameterWithKey:(NSString *)key fromUrlString:(NSString *)urlString {
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return nil;
    }
    if (![key isKindOfClass:NSString.class] || key.length <= 0) {
        return nil;
    }
    NSError *error;
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *matches = [regex matchesInString:urlString
                                      options:0
                                        range:NSMakeRange(0, [urlString length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [urlString substringWithRange:[match rangeAtIndex:2]];
        return tagValue;
    }
    return nil;
}

+ (NSString *)replaceParameterKey:(NSString *)key withValue:(NSString *)value toUrlString:(NSString *)urlString {
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return urlString;
    }
    if (![key isKindOfClass:NSString.class] || key.length <= 0) {
        return urlString;
    }
    if (!value) {
        return urlString;
    }
    NSError *error;
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *matches = [regex matchesInString:urlString
                                      options:0
                                        range:NSMakeRange(0, [urlString length])];
    NSString *result = urlString;
    for (NSTextCheckingResult *match in matches) {
        result = [urlString stringByReplacingCharactersInRange:[match rangeAtIndex:2] withString:value];
        return result;
    }
    return result;
}

+ (NSString *)addUrlParameters:(NSDictionary *)params toUrlString:(NSString *)urlString {
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return urlString;
    }
    //初始化参数变量
    NSString *paramsString = @"&";
    if ([urlString containsString:@"?"]) {
        paramsString = @"&";
    } else {
        paramsString = @"?";
    }
    //快速遍历参数数组
    for (id key in [params allKeys]) {
        NSString *keyValue = key;
        if (![keyValue isKindOfClass:NSString.class]) {
            keyValue = [NSString stringWithFormat:@"%@", key];
        }
        paramsString = [paramsString stringByAppendingString:keyValue];
        paramsString = [paramsString stringByAppendingString:@"="];
        NSString *value = [params objectForKey:key];
        if (![value isKindOfClass:NSString.class]) {
            value = [NSString stringWithFormat:@"%@", value];
        }
        paramsString = [paramsString stringByAppendingString:value];
        paramsString = [paramsString stringByAppendingString:@"&"];
    }
    // 处理多余的&以及返回含参url
    if (paramsString.length > 1 && [paramsString hasSuffix:@"&"]) {
        // 去掉末尾的&
        paramsString = [paramsString substringToIndex:paramsString.length - 1];
        // 返回含参url
        return [urlString stringByAppendingString:paramsString];
    }
    return urlString;
}

+ (NSString *)removeParameterWithKey:(NSString *)key toUrlString:(NSString *)urlString {
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return urlString;
    }
    if (![key isKindOfClass:NSString.class] || key.length <= 0) {
        return urlString;
    }
    NSError *error;
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *matches = [regex matchesInString:urlString
                                      options:0
                                        range:NSMakeRange(0, [urlString length])];
    NSString *result = urlString;
    for (NSTextCheckingResult *match in matches) {
        NSRange range = match.range;
        //正则表达式匹配到的有以下会有两种参数：&xxx=xxx, ?xxx=xxx, 如果是?,则保留
        range = NSMakeRange(match.range.location + 1, match.range.length - 1);
        result = [urlString stringByReplacingCharactersInRange:range withString:@""];
        if ([result hasSuffix:@"&"] && result.length >= 1) {
            result = [result substringToIndex:result.length - 1];
        }
        return result;
    }
    return result;
}

+ (NSString *)formatDateStringForChatFromTimeInterval:(NSTimeInterval)timeInterval dateFormatter:(NSDateFormatter *)dateFormatter {
    NSString *dateString = nil;
    if (timeInterval < 1) {
        return dateString;
    }
    NSInteger timeToDisplay = 0;
    NSDate *showDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSTimeInterval timeSinceLastUpdate = -1 * [showDate timeIntervalSinceNow] - 600;
    if(timeSinceLastUpdate < 3600) {
        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 60);
        if (timeToDisplay < 2) {
            dateString = [NSString stringWithFormat:@"刚刚"];
        } else {
            dateString = [NSString stringWithFormat:@"%ld分钟前",(long)timeToDisplay];
        }
    } else if (timeSinceLastUpdate < 86400) {
        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 3600);
        dateString = [NSString stringWithFormat:@"%ld小时前",(long)timeToDisplay];
    } else if (timeSinceLastUpdate < 2592000) {
        timeToDisplay = (NSInteger) (timeSinceLastUpdate / 86400);
        dateString = [NSString stringWithFormat:@"%ld天前",(long)timeToDisplay];
    } else {
        if (!dateFormatter) {
            dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy.MM.dd"];
        }
        dateString = [dateFormatter stringFromDate:showDate];
    }
    return dateString;
}

@end
